package util;

import java.util.Optional;


/**
 * Optional使用
 */
public class OptionalUtils {
    public static void main(String[] args) {
//        of();
//        ofNullable();
//        empty();
//        get();
        ifPresent();
        orElse();
        use();
    }

    private static void use() {
        String name = Optional.of(new Person("Tom", 18)).map(Person::getName).map(String::toUpperCase).orElse(null);
        System.out.println("name = " + name);
    }

    private static void orElse() {
        Optional.empty().orElse("no value");
    }

    private static void ifPresent() {
        Optional.of("hello").ifPresent(System.out::println);
    }

    private static void get() {
        Optional<String> o1 = Optional.of("hello");
        String s = o1.get();//如果无值则会报错
        System.out.println("s = " + s);
    }

    private static void empty() {
        Optional<Object> empty = Optional.empty();//存入的是null
        System.out.println("empty.isPresent() = " + empty.isPresent());//false
    }

    private static void ofNullable() {
        Optional<Object> o1 = Optional.ofNullable(null); // 既可以传具体值，也可以传null
        Optional<Object> o2 = Optional.ofNullable("hello");
    }

    private static void of() {
        Optional<String> o1 = Optional.of("hello");
        Optional<String> o2 = Optional.of(null); // 只能传具体值，不能传Null，否则报空指针

    }
}

class Person{
    private String name;
    private Integer age;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}